using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Demo.Identity.Permissions.Dto;
using Demo.Identity.Permissions.Entities;
using Volo.Abp.Domain.Repositories;

namespace Demo.Identity.Permissions
{
    /// <summary>
    /// 角色管理应用服务
    /// </summary>
    public class RolePermissionsAppService : IdentityAppService, IRolePermissionsAppService
    {
        #region 初始化
        private readonly IRepository<RolePermissions> _rolePermissionsRepository;
        private readonly IRepository<SysPermission> _sysPermissionsRepository;
        
        public RolePermissionsAppService(
            IRepository<RolePermissions> rolePermissionsRepository,
            IRepository<SysPermission> sysPermissionsRepository
            )
        {
            _rolePermissionsRepository = rolePermissionsRepository;
            _sysPermissionsRepository = sysPermissionsRepository;
        }
        #endregion


        #region 获取角色所有权限
        /// <summary>
        /// 获取角色所有权限
        /// </summary>
        /// <param name="roleId">角色ID</param>
        /// <returns></returns>
        public async Task<List<PermissionTreeDto>> GetPermission(Guid roleId)
        {
            var query = from rp in (await _rolePermissionsRepository.GetQueryableAsync())
                    .Where(x => x.RoleId == roleId)
                join permission in (await _sysPermissionsRepository.GetQueryableAsync())
                    on rp.PermissionId equals permission.Id
                select permission;
            var permissions = await AsyncExecuter.ToListAsync(query);
            var lst = ObjectMapper.Map<List<SysPermission>, List<PermissionTreeDto>>(permissions);
            return PermissionTreeBuilder.Build(lst);
        }
        #endregion

        #region 设置角色权限
        /// <summary>
        /// 设置角色权限
        /// </summary>
        /// <param name="roleId">橘色编号</param>
        /// <param name="permissions">权限编号</param>
        /// <returns></returns>
        public async Task SetPermission(SetRolePermissionsDto dto)
        {
            await _rolePermissionsRepository.DeleteAsync(x => x.RoleId == dto.RoleId);
            foreach (var permissionId in dto.Permissions)
            {
                RolePermissions entity = new RolePermissions()
                {
                    PermissionId = permissionId,
                    RoleId = dto.RoleId,
                };
                await _rolePermissionsRepository.InsertAsync(entity);
            }
        }
        #endregion

    }
}
